﻿using System.Collections.Concurrent;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using MongoDB.Driver;
using WebApplication1.Models;
using WebApplication1.Repository;

namespace WebApplication1;

[Authorize] // 👈 只允许认证用户连接
public class ChatHub : Hub
{
    // 使用线程安全集合存储在线用户
    private static readonly ConcurrentDictionary<string, string> _users = new();
    private readonly ChatMessageRepository _repository;
    private readonly IMongoCollection<ChatMessage> _lobbyCollection;
    private readonly IMongoCollection<ChatMessage> _groupCollection;
    private readonly IMongoCollection<ChatMessage> _privateCollection;

    public ChatHub(IMongoDatabase database,ChatMessageRepository repository)
    {
        _lobbyCollection = database.GetCollection<ChatMessage>("LobbyMessages");
        _groupCollection = database.GetCollection<ChatMessage>("GroupMessages");
        _privateCollection = database.GetCollection<ChatMessage>("PrivateMessages");

        _repository = repository;
    }


    public async Task SendMessage(string user, string message)
    {
        var fromUserId = Context.UserIdentifier;
        if (string.IsNullOrWhiteSpace(fromUserId)) return;

        // 创建 ChatMessage 实例
        var chatMessage = new ChatMessage
        {
            FromUserId = fromUserId,
            Content = message,
            ToUserId = "Lobby", // 大厅组名
            Timestamp = DateTime.UtcNow
        };

        await _lobbyCollection.InsertOneAsync(chatMessage);
        // 向所有连接的客户端广播消息
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }



    // 发送消息给指定用户
    public async Task SendPrivateMessage(string toUserId, string message)
    {
        var fromUserId = Context.UserIdentifier;
        if (string.IsNullOrWhiteSpace(fromUserId)) return;

        // 创建 ChatMessage 实例
        var chatMessage = new ChatMessage
        {
            FromUserId  = fromUserId,
            Content = message,
            ToUserId  = toUserId,
            Timestamp = DateTime.UtcNow
        };

        await _privateCollection.InsertOneAsync(chatMessage);

        // 2. 发送给接收方
        await Clients.User(toUserId).SendAsync("ReceivePrivateMessage", fromUserId, message, chatMessage.Timestamp);

        // 3. 也回显给发送者
        await Clients.User(fromUserId).SendAsync("ReceivePrivateMessage", fromUserId, message, chatMessage.Timestamp);
    }

    // 用户加入群组
    public async Task JoinGroup(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("UserJoined", Context.User?.Identity?.Name ?? Context.ConnectionId);
    }

    // 用户离开群组
    public async Task LeaveGroup(string groupName)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("UserLeft", Context.User?.Identity?.Name ?? Context.ConnectionId);
    }

    public override Task OnConnectedAsync()
    {

        var userId = Context.UserIdentifier;
        if (!string.IsNullOrWhiteSpace(userId))
        {
            _users.TryAdd(Context.ConnectionId, userId);

        };


        // 广播在线用户列表
        BroadcastUsers();

        return base.OnConnectedAsync();
    }

   
    public override Task OnDisconnectedAsync(Exception? exception)
    {
        if (_users.TryRemove(Context.ConnectionId, out var username))
        {
            BroadcastUsers();
        }

        return base.OnDisconnectedAsync(exception);
    }
    private void BroadcastUsers()
    {
        var users = _users.Values.Distinct().ToList();
        Clients.All.SendAsync("UpdateUserList", users);
    }

}